package com.dhf.framework.common.log;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.CollectionUtils;

import com.dhf.framework.base.utils.CommonUtils;
import com.dhf.framework.base.utils.SpringContextHolder;
import com.dhf.framework.common.Constants;
import com.dhf.framework.system.dao.SysLogDao;
import com.dhf.framework.system.entity.SysLog;
import com.dhf.framework.system.entity.SysUser;
import com.dhf.framework.system.service.SysMenuService;

/**
 * 
* @ClassName: SaveLog
* @Description: 保存日志
* @author 
*
 */
public class LogUtils {
	
	public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
	
	private static SysLogDao sysLogDao = SpringContextHolder.getBean(SysLogDao.class);
	
    private static SysMenuService sysMenuService = SpringContextHolder.getBean(SysMenuService.class);
	
	
    
    
    /**
     * 设置请求参数
     * @param paramMap
     */
    public static String setParams(Map<String, String[]> paramMap){
        if (!CollectionUtils.isEmpty(paramMap)){
            return "";
        }
        StringBuilder params = new StringBuilder();
        Iterator<String> keys = paramMap.keySet().iterator();
        while(keys.hasNext()) {
            String key = (String) keys.next();
            String value=paramMap.get(key).toString();
            params.append(key+"="+value+"&");
        }
        return  params.toString().substring(0, params.length());
    }
    
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, Object handler, Exception ex){
	    SysUser sysUser=(SysUser) request.getSession().getAttribute(Constants.SESSION_USER_KEY);
        String url=request.getRequestURI();
        
        SysLog sysLog = new SysLog();
        sysLog.setType(ex == null ? sysLog.TYPE_ACCESS : sysLog.TYPE_EXCEPTION);
        sysLog.setRemoteAddr(CommonUtils.getRemoteAddr(request));
        sysLog.setUserAgent(request.getHeader("user-agent"));
        sysLog.setRequestUri(url);
        sysLog.setMethod(request.getMethod());
        sysLog.setParams(setParams(request.getParameterMap()));
        sysLog.setException(ex== null ? "":ex.getMessage());
        sysLog.setCreateUser(sysUser==null?"":  sysUser.getLoginName());
        sysLog.setCreateDate(new Date());
        
        String path=request.getServletPath();
        String menuName=sysMenuService.queryMenuNameByMenuUrl(path);
        sysLog.setTitle(menuName);
        // 保存日志信息
        // 异步保存日志
        new SaveLogThread(sysLog).start();
	}

	/**
	 * 保存日志线程
	 */
	public static class SaveLogThread extends Thread{
		
		private SysLog sysLog;
		
		public SaveLogThread(SysLog sysLog){
			super(SaveLogThread.class.getSimpleName());
			this.sysLog = sysLog;
		}
		
		@Override
		public void run() {
			sysLogDao.add(sysLog);
		}
	}
	
}
